import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/components/base_components/base_filter_select_chip.dart';
import 'package:x3_component_core/components/selector_components/base_filter_selector.dart';
import 'package:x3_component_core/models/base_advanced_filter_model.dart';

class BaseFilterMultiple extends StatefulWidget {
  final AdvancedFilterModel model;
  final Map<String, dynamic> dataSource;

  const BaseFilterMultiple({Key key, @required this.model, @required this.dataSource})
      : assert(model != null),
        super(key: key);
  @override
  _BaseFilterMultipleState createState() => _BaseFilterMultipleState();
}

class _BaseFilterMultipleState extends State<BaseFilterMultiple> with AutomaticKeepAliveClientMixin {
  AdvancedFilterModel get model => widget.model;
  Map<String, dynamic> get _dataSource => widget.dataSource;
  @override
  Widget build(BuildContext context) {
    super.build(context);

    List<String> _dataList = _dataSource[model.tagId] as List<String>;
    String _selectedText = model.tags.where((element) => _dataList.contains(element.key)).toList().map((e) => e.value).join(',');
    List<Widget> _children = [];
    for (BaseKeyValueModel e in model.tags) {
      bool selected = _dataList.contains(e.key);
      _children.add(BaseFilterSelectChip(
          selected: selected,
          label: e.value,
          onSelected: (bool) {
            String _currentKey = e.key;
            setState(() {
              // 选择不限
              if (_currentKey == '-2') return _dataSource[model.tagId] = ['-2'];
              // 去除不限选项
              _dataList.remove('-2');
              if (bool == false) {
                _dataList.remove(e.key);
                // 如果什么都没有选择 默认选不限
                if (_dataList.length == 0) _dataList = ['-2'];
              } else {
                _dataList.add(e.key);
                // 子项全部选中 默认选不限
                if ((!_dataList.contains('-2') && _dataList.length == model.tags.length - 1)) _dataSource[model.tagId] = ['-2'];
              }
            });
          }));
    }
    return BaseFilterSelector(
      title: model.tagName,
      selectedText: _selectedText,
      children: _children,
      isExpanded: model.tagIsExpanded,
      onChange: (bool state) {
        model.tagIsExpanded = state;
      },
    );
  }

  @override
  bool get wantKeepAlive => true;
}
